package com.example.nomemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;//不要选错啦！
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class NewsActivity extends AppCompatActivity implements Runnable, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    Handler handler;
    private static final String TAG = "NewsActivity";
    private ArrayList<HashMap<String, String>> listItems;//存放文字、图片信息
    private SimpleAdapter listItemAdatper;
    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_main);
        SharedPreferences sp = getSharedPreferences("time", Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");
        Log.i("List", "lastRateDateStr=" + logDate);

        initListView();
        listView=(ListView) findViewById(R.id.listview);
        listView.setAdapter(listItemAdatper);
        Thread t = new Thread(this);
        t.start();
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 7) {
                    listItems = (ArrayList<HashMap<String, String>>) msg.obj;//list包要导入正确
                    listItemAdatper = new SimpleAdapter(NewsActivity.this, listItems,
                            R.layout.activity_news,//xml布局实现
                            new String[]{"ItemTitle", "ItemDetail"},
                            new int[]{R.id.itemTitle, R.id.itemDetail}
                    );
                    listView.setAdapter(listItemAdatper);
                }
                super.handleMessage(msg);
            }
        };
        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.news, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu) {
            Intent config = new Intent(this, MainActivity.class);
            startActivity(config);
        }
        return super.onOptionsItemSelected(item);
    }

    private void initListView() {
        listItems = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < 10; i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("ItemTitle", "rate: " + i);//标题文字
            map.put("ItemDetail", "detail" + i);//详情描述
            listItems.add(map);
        }
        //生成适配器 的item和动态数组对应的元素
        listItemAdatper = new SimpleAdapter(this, listItems,
                R.layout.activity_news,//xml布局实现
                new String[]{"ItemTitle", "ItemDetail"},
                new int[]{R.id.itemTitle, R.id.itemDetail}
        );
    }

    @Override
    public void run() {
        List<HashMap<String, String>> retList = new ArrayList<HashMap<String, String>>();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i("run", "curDateStr:" + curDateStr + " logDate:" + logDate);

        Log.i(TAG, "run: run()....");

        Document doc = null;
        try {
            doc = Jsoup.connect("https://it.swufe.edu.cn/index/tzgg.htm").get();
            Log.i(TAG, "run: title" + doc.title());
            Elements spans = doc.getElementsByTag("span");
            Log.i(TAG, "run: spans.size:" + spans.size());
            //根据学院通知公告栏特点进行删除span，前七个和最后三个都是无用数据
            for (int i = 0; i < 7; i++)
                spans.remove(0);//删除前七个span
            Log.i(TAG, "run: spans.size:" + spans.size());
            while (spans.size() > 3) {//最后三个span也不能要
                Log.i(TAG, "run: title" + spans.get(0).text());
                //spans.get(0);
                Log.i(TAG, "run: time" + spans.get(1).text());
                //spans.get(1);
                HashMap<String, String> map = new HashMap<String, String>();
                String str1 = spans.get(0).text();
                String str2 = spans.get(1).text();

                map.put("ItemTitle", str1);
                map.put("ItemDetail", str2);
                retList.add(map);
                spans.remove(0);
                spans.remove(0);
            }

            //获取超链接,目前已获取完成，但是怎么存，怎么用
            Elements links = doc.getElementsByTag("a");
            //Log.i(TAG, "run: herf:"+links);
            for (Element link : links) {
                String linkhref = link.attr("href");
                if (linkhref.startsWith("../info/")) {
                    String fullLink = "https://it.swufe.edu.cn/" + linkhref;
                    Log.i(TAG, "run: link:" + fullLink);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Message msg = handler.obtainMessage(7);
        msg.obj = retList;
        handler.sendMessage(msg);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //希望能够实现跳转页面
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i(TAG, "onItemLongClick: 长按操作");
        AlertDialog.Builder bulider = new AlertDialog.Builder(this);
        bulider.setTitle("提示")
                .setMessage("确认是否添加到备忘中？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //存入到数据库
                        String Str1, Str2;
                        HashMap<String, String> str2;
                        str2 = listItems.get(position);
                        Log.i(TAG, "onClick: str2=" + str2);
                        Str1 = str2.get("ItemTitle");
                        Str2 = str2.get("ItemDetail");
                        NoticeManager manager = new NoticeManager(NewsActivity.this);
                        //manger.deleteAll();
                        //manger.addAll(all);
                        manager.add(new NoticeItem(Str1, Str2));
                        Log.i(TAG, "onClick: 数据库存储完毕");
                        List<NoticeItem> all = manager.listAll();
                        for(NoticeItem i:all){
                            Log.i(TAG, "onCreate: 取出数据：title="+i.getNotTitle());
                            Log.i(TAG, "onCreate: 取出数据：time="+i.getNotTime());
                        }
                        //测试删除数据
                    }
                }).setNegativeButton("否", null);
        bulider.create().show();
        return true;
        //变为true：长按操作返回后会与单击区分开
    }
}